/*
 * @Author: pao
 * @Date:   2016-12-30 23:50:54
 * @Last Modified by:   pao
 * @Last Modified time: 2017-01-04 18:48:13
 */

'use strict';
const fs = require('fs');


exports.getLoginPage = (req, res) => {
	//登录页面一般是首次登录和退出登录才会出现，
	//当用户退出时，跳转到登录页面，此时需要清空服务器保存的uname
	req.session.uname=null;

    //此控制器模块导入路由模块，路由模块再导入到服务器开启所在文件，读取文件的文件路径要以服务器开启所在文件为参照
    fs.readFile('./view/login.html', (err, content) => {
        if (err) {
            console.log(err);
            return;
        }
        res.setHeader('Content-Type','text/html;charset=utf-8')
        res.end(content);
    })

}

exports.login=(req,res)=>{

	// res.writeHead(200,{'Content-Type':'application/x-javascript;charset=utf-8'})
	//验证用户名和密码之前先验证验证码是否有误
	if(+req.body.vcode!==req.session.vcode){

		res.end("<script charset='utf-8'>alert('验证码有误');window.location='/account/login'</script>")
	}

	req.models.user.find({uname:req.body.uname,upwd:req.body.upwd},(err,users)=>{
		if(err){
			console.log(err);
			return;
		}
		if(users!=null&&users.length===1){
			req.session.uname=req.body.uname;
			res.end("<script charset='utf-8'>alert('登录成功');window.location='/video/list'</script>")
		}else{
			res.end("<script charset='utf-8'>alert('用户名或密码有误');window.location='/account/login'</script>")
		}
	})
}

//导入生成验证码的第三方包
const captchapng=require('captchapng');

exports.getCaptchapng=(req,res)=>{
	const vcode=parseInt(Math.random()*9000+1000);
	req.session.vcode=vcode;//将验证码保存在session中
	const p = new captchapng(80,30,vcode); // width,height,numeric captcha 
        p.color(0, 0, 0, 0);  // First color: background (red, green, blue, alpha) 
        p.color(80, 80, 80, 255); // Second color: paint (red, green, blue, alpha) 
 
        var img = p.getBase64();
        var imgbase64 = new Buffer(img,'base64');
        res.setHeader('Content-Type','image/png');
        res.end(imgbase64);
}
